package com.SpringBoot.cart.service;

import com.SpringBoot.Util.Result;
import com.SpringBoot.cart.Dto.CartDto;
import com.SpringBoot.cart.mapper.CartMapper;
import com.SpringBoot.cart.pojo.Cart;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bxk
 * @since 2025-09-15
 */
@Service
public class CartService {

    private final CartMapper cartMapper;

    public CartService(CartMapper cartMapper) {
        this.cartMapper = cartMapper;
    }

    public Result addCart(Cart cart) {
        Cart existCart = cartMapper.selectCartByid(cart.getUserId(), cart.getProductId());

        if(existCart == null) {
            cartMapper.addCart(cart);
            return Result.success("添加成功");
        }
        else  {
            cart.setCartId(existCart.getCartId());
            if(Objects.equals(existCart.getIsDeleted(), 1)){
                existCart.setIsDeleted(0);
                cartMapper.deleteCart(existCart);
                cart.setCreatedAt(LocalDateTime.now());
                cartMapper.updateCart(cart);
                return Result.success("添加成功");
            }
            else {
                cart.setQuantity(existCart.getQuantity() + cart.getQuantity());
                return updateCart(cart);
            }
        }
    }

    public Result updateCart(Cart cart) {
        if(cart.getQuantity() != 1){
            cartMapper.updateCart(cart);
            return Result.success("添加成功");
        }
        else {
            cart.setQuantity(cart.getQuantity() + 1);
            return Result.success("添加成功");
        }
    }


    public Result deleteCart(Cart cart) {
        cart.setIsDeleted(1);
        cartMapper.deleteCart(cart);
        return Result.success("删除成功");

    }

    public Result selectByUserId(Integer userId) {
        List<CartDto> cartList = cartMapper.selectCartByUserId(userId);
        if(cartList == null || cartList.isEmpty()){
            return Result.error(404,"您的购物车为空");
        }else{
            return Result.success(cartList);
        }
    }


}
